package com.yu.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.task.mapper.BlogTagMapper;
import com.yu.task.pojo.BlogTag;
import com.yu.task.service.BlogTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class BlogTagServiceImpl extends ServiceImpl<BlogTagMapper, BlogTag> implements BlogTagService {
    @Autowired
    private BlogTagMapper blogTagMapper;
    @Override
    public int insertBlogTag(BlogTag[] blogTags) {
        try {
            int j=0;
            for (int i = 0; i < blogTags.length; i++) {
                blogTags[i].setCreateTime(new Date());
                QueryWrapper<BlogTag> qw = new QueryWrapper<>();
                qw.eq("blog_id", blogTags[i].getBlogId()).eq("tag_id",blogTags[i].getTagId());
                BlogTag blogTagOne = blogTagMapper.selectOne(qw);
                if(blogTagOne == null) {
                    j = blogTagMapper.insert(blogTags[i]) + j;
                }else {
                    break;
                }
            }
            return j;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateBlogTags(BlogTag[] blogTags) {
        try {
            QueryWrapper<BlogTag> qw = new QueryWrapper<>();
            Long bId = blogTags[0].getBlogId();
            qw.eq("blog_id",bId);
            int j=0;

            blogTagMapper.delete(qw);
            for (int i = 0; i < blogTags.length; i++) {
                blogTags[i].setCreateTime(new Date());
                int blogTagOne = blogTagMapper.insert(blogTags[i]);
                if(blogTagOne == 1) {
                    j++;
                }else {
                    break;
                }
            }
            return j;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteByTagId(Long blogId,Long tagId) {
        try {
            QueryWrapper<BlogTag> qw = new QueryWrapper<>();
            qw.eq("tag_id",tagId).eq("blog_id",blogId);
            int i =blogTagMapper.delete(qw);
            return i;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
